package com.wl.util;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.wl.constant.Constant;
import com.wl.pojo.model.UserToken;
import com.wl.response.CommonReturnType;
import lombok.SneakyThrows;
import redis.clients.jedis.Jedis;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @program: treeHole
 * @author: 吴磊
 * @create: 2021-07-08 17:51
 */
@MultipartConfig
public class FTPUtil {
    private Myproperties myproperties = Myproperties.getMyProperties();

    @SneakyThrows
    public void sshSftp(HttpServletRequest request, HttpServletResponse response, byte[] bytes, String fileName) {
        Session session;
        Channel channel = null;
        JSch jsch = new JSch();
        //连接服务器，采用默认端口
        session = jsch.getSession(myproperties.getProperty("ftpCentos.user"),
                myproperties.getProperty("ftpCentos.host"),
                Integer.parseInt(myproperties.getProperty("ftpCentos.port")));
        //如果服务器连接不上，则抛出异常
        if (session == null) {
            MyUtil.responseData(response, CommonReturnType.fail("服务器连接失败"));
            return;
        }
        //设置登陆主机的密码
        session.setPassword(myproperties.getProperty("ftpCentos.password"));
        //设置第一次登陆的时候提示，可选值：(ask | yes | no)
        session.setConfig("StrictHostKeyChecking", "no");
        //设置登陆超时时间
        try {
            session.connect(30000);
        } catch (Exception e) {
            MyUtil.responseData(response, CommonReturnType.fail("服务器连接超时"));
            return;
        }
        OutputStream os = null;
        try {
            //创建sftp通信通道
            channel = session.openChannel("sftp");
            channel.connect(1000);
            ChannelSftp sftp = (ChannelSftp) channel;
            //进入服务器指定的文件夹
            try {
                sftp.cd(getStringDir());
            } catch (Exception e) {
                sftp.mkdir(getStringDir());
                sftp.cd(getStringDir());
            }
            //以下代码实现从本地上传一个文件到服务器，如果要实现下载，对换以下流就可以了
            os = sftp.put(fileName);
            os.write(bytes);
            os.flush();
        } catch (Exception e) {
            MyUtil.responseData(response, CommonReturnType.fail("文件上传失败"));
        } finally {
            //关流操作
            if (os != null) {
                os.flush();
                os.close();
            }
            if (session != null) {
                session.disconnect();
            }
            if (channel != null) {
                channel.disconnect();
            }
        }
    }

    /**
     * 上传文件
     *
     * @param request
     * @return 返回文件路径
     */
    @SneakyThrows
    public String uploadFolder(HttpServletRequest request, HttpServletResponse response) {
        Part part = request.getPart("file");
        int size = (int) part.getSize();
        InputStream is = part.getInputStream();
        byte[] bytes = new byte[size];
        is.read(bytes);
        String fileName = part.getSubmittedFileName();
        UserToken userToken = TokenUtils.getUser(request);
        String userId = userToken.getUserId();
        Jedis jedis = RedisUtil.getJedis();
        String newName;
        if (Boolean.TRUE.equals(jedis.sismember(Constant.USER_PICURL, userId + "-1"))) {
            jedis.srem(Constant.USER_PICURL, userId + "-1");
            jedis.sadd(Constant.USER_PICURL, userId + "-2");
            newName = userId + "-2" + fileName.substring(fileName.lastIndexOf('.'));
        } else if (Boolean.TRUE.equals(jedis.sismember(Constant.USER_PICURL, userId + "-2"))) {
            jedis.srem(Constant.USER_PICURL, userId + "-2");
            jedis.sadd(Constant.USER_PICURL, userId + "-1");
            newName = userId + "-1" + fileName.substring(fileName.lastIndexOf('.'));
        } else {
            jedis.sadd(Constant.USER_PICURL, userId + "-1");
            newName = userId + "-1" + fileName.substring(fileName.lastIndexOf('.'));
        }
        jedis.close();
        sshSftp(request, response, bytes, newName);
        return "http://121.4.192.88:9876/image/treeHole/user/" + getStringDir() + newName;
    }

    public String getStringDir() {
        return myproperties.getProperty("ftpCentos.basePath") + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/";
    }
}
